﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;

// ej: http://televoyeur.com/compus.aspx?key=mago

public partial class compus : System.Web.UI.Page
{
    protected void Page_Load (object sender, EventArgs e)
    {
        bool esGet = Request.RequestType.CompareTo("GET") == 0;

        string ident = esGet ? Request.QueryString["ident"] : Request.Form["ident"];

        using (SqlConnection conn = new SqlConnection("Data Source=localhost;Initial Catalog=w1701119_televoyeurdb;Integrated Security=SSPI;"))
        {
            try
            {
                conn.Open();

                string ret = upsertar (
                    conn,
                    ident,
                    IPHelper.getClientIP (HttpContext.Current.Request)
                );

                Response.Write (ret);
            }
            catch (Exception exx)
            {
                Response.Write(exx.Message);
            }
            finally
            {
                conn.Close();
            }
        }
    }

    public string upsertar (SqlConnection conn, string ident, string ip)
    {
        string val = string.Format("ident={0}, ip={1}", ident, ip);

        try
        {
            string sqlUpdate = "update compus set ip = '[IP]' where ident like '[KEY]'";
            sqlUpdate = sqlUpdate.Replace("[IP]" , ip);
            sqlUpdate = sqlUpdate.Replace("[KEY]", ident);
            SqlCommand cmdUpdate = new SqlCommand(sqlUpdate, conn);

            if (1 == cmdUpdate.ExecuteNonQuery())
            {
                return "UPDATE -> " + val;
            }
            else
            {
                string sqlInsert = "insert into compus (ident, ip) values ('[KEY]', '[IP]')";
                sqlInsert = sqlInsert.Replace("[IP]" , ip );
                sqlInsert = sqlInsert.Replace("[KEY]", ident);
                SqlCommand cmdInsert = new SqlCommand(sqlInsert, conn);
                cmdInsert.ExecuteNonQuery();
                return "INSERT -> " + val;
            }
        }
        catch (Exception exx)
        {
            return "ERROR -> " + val + " -> " + exx.ToString();
        }
    }
}
